package com.zhida.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.ConnectException;

/**
 * Create by zhh 2024/7/4 23:58
 */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // TODO 模拟登录校验
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        if(headers.get("token") == null){
            return chain.filter(exchange);
        }
        String userInfo = headers.get("token").get(0);
        System.err.println("headers = " + headers);
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("token", userInfo))
                .build();
        return chain.filter(swe);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
